package com.lhd.dbpool;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 类 {@code PoolUtil1} 数据库连接池工具1.
 *
 * <p>主要包括 初始化连接池、关闭连接、释放连接等功能，写死数据库连接信息在代码
 *
 * @author MapLover
 * @see PoolUtil
 * @since 2020.09
 */
@Slf4j
public class PoolUtil2 {

    private static final BasicDataSource dataSource = new BasicDataSource();

    // 配置数据源
    static {
        log.info("---init data source pool----------");
        dataSourceConfig();
    }

    // 以代码形式，设置数据源各属性值
    private static void dataSourceConfig() {
//        dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
//        dataSource.setUrl("jdbc:oracle:thin:@localhost:1521:ORCL");

        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUrl("jdbc:postgresql://localhost:5432/test");
        dataSource.setUsername("sdr");
        dataSource.setPassword("sdr#2020");

        dataSource.setInitialSize(10);
        dataSource.setMaxTotal(300);
        dataSource.setMaxIdle(40);
        dataSource.setMinIdle(20);
        dataSource.setMaxWaitMillis(6000);

        log.info("---init DataSourceConfig OK----------");
    }

    // 获得连接对象
    public static Connection getConnection() {
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            log.info("----get Postgres Connection----------");
        } catch (SQLException e) {
            log.error(e.getMessage());
        }
        return conn;
    }

    public static void release(Connection conn, Statement st, ResultSet rs) {
        if (rs != null) {
            try {
                // 关闭存储查询结果的ResultSet对象
                rs.close();
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }

        if (st != null) {
            try {
                st.close();
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }

        if (conn != null) {
            try {
                // 将Connection连接对象还给数据库连接池
                conn.close();
            } catch (Exception e) {
                log.error(e.getMessage());
            }
        }
    }


    public static void main(String[] args)  {
        PoolUtil2.getConnection();
    }
}
